package cn.tsvtc.shop.controller;

import cn.tsvtc.shop.entity.ResultMessage;
import cn.tsvtc.shop.pojo.Product;
import cn.tsvtc.shop.service.ProductService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @author: Athena
 * @date: 2020/11/3 19:43
 * @description:
 */
@RestController
@RequestMapping("product")
public class ProductController {

    private ProductService productService;

    private Configuration configuration;

    @Autowired
    public ProductController(ProductService productService,Configuration configuration){
        this.productService=productService;
        this.configuration=configuration;
    }

    @Value("${pagepath}")
    private String path;


    @GetMapping("init")
    public ResultMessage init(){
        List<Product> products = productService.findAll();
        FileWriter fileWriter=null;
        try {
            for (Product product : products) {

                fileWriter=new FileWriter(path+"product"+product.getId()+".html");
                Template template = configuration.getTemplate("introduction.ftl");
                template.process(product,fileWriter);
            }
            return new ResultMessage(true,"succeed",products);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMessage(false,"failed",e.getMessage());
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


}
